# !/usr/local/bin/python3
# -*- encoding: utf-8 -*-
# @FileName :   Dialog.py
# @DateTime :   2022/8/25 | 17:50
# @Author   :   IoTus3
# @GitHub   :   https://gitee.com/IoTus3
# @Contact  :   xianglin.fu3@gmail.com
# @License  :   (C)Copyright 2022-2023, LinYuStudio-NLPR-CASIA
# @Editor   :   Power by PyCharm
# @Desc     :   None


# 引入PySide6
from PySide6.QtWidgets import *
from PySide6.QtCore import Qt

# 引入系统库
import os
import json

# 引入第三方库
from src.main.conf.conf import smtpPath, proxyPath, logPath


class SMTPDialog(QDialog):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.field_dict = {}
        self.init_ui()

    def init_ui(self):
        """
        初始化对话框
        :return:
        """
        self.setWindowTitle("报警邮件配置")
        self.resize(300, 270)

        layout = QVBoxLayout()

        form_data_list = [
            {"title": "SMTP服务器", "field": "smtp"},
            {"title": "发件箱", "field": "from"},
            {"title": "密码", "field": "pwd"},
            {"title": "收件人(多个用逗号隔开)", "field": "to"},
        ]

        # 读取文件中的配置
        data_dict = {}
        if os.path.exists(smtpPath):
            fp = open(smtpPath, mode="r", encoding="utf-8")
            data_dict = json.load(fp)
            fp.close()

        for item in form_data_list:
            lbl = QLabel()
            lbl.setText(item['title'])
            layout.addWidget(lbl)
            txt = QLineEdit()
            layout.addWidget(txt)
            field = item['field']
            if data_dict and field in data_dict:
                txt.setText(data_dict[field])
            self.field_dict[item['field']] = txt

        btn_save = QPushButton("保存")
        btn_save.clicked.connect(self.EventSaveClicked)
        layout.addWidget(btn_save, 0, Qt.AlignRight)

        layout.addStretch(1)
        self.setLayout(layout)

    def EventSaveClicked(self):
        data_dict = {}
        for key, field in self.field_dict.items():
            value = field.text().strip()
            if not value:
                QMessageBox.warning(self, "错误", "邮件设置不能为空")
                return
            data_dict[key] = value
        try:
            with open(smtpPath, mode="w", encoding="utf-8") as fp:
                json.dump(data_dict, fp)
            QMessageBox.warning(self, "成功", "smtp信息保存成功")
        except Exception as e:
            QMessageBox.warning(self, "失败", str(e))

        self.close()


class ProxyDialog(QDialog):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("配置代理IP")
        self.resize(500, 400)
        layout = QVBoxLayout()

        # 输入框
        text_edit = QTextEdit()
        text_edit.setPlaceholderText("可用换行来设置多个代理，每个代理IP设置格式为：31.40.255.250:8080")

        # 读取代理文件
        all_proxy = ""
        if os.path.exists(proxyPath):
            with open(proxyPath, mode="r", encoding="utf-8") as fp:
                all_proxy = fp.read()

        text_edit.setText(all_proxy)
        self.text_edit = text_edit
        layout.addWidget(text_edit)

        footer_config = QHBoxLayout()
        btn_save = QPushButton("保存并重置")
        btn_save.clicked.connect(self.EventSaveClicked)
        footer_config.addWidget(btn_save, 0, Qt.AlignRight)

        layout.addLayout(footer_config)

        self.setLayout(layout)

    def EventSaveClicked(self):
        # 写入到代理文件中
        text = self.text_edit.toPlainText()
        with open(proxyPath, mode="w", encoding="utf-8") as fp:
            fp.write(text)

        self.close()


class LogDialog(QDialog):

    def __init__(self, asin, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.asin = asin
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("日志记录")
        self.resize(500, 400)
        layout = QVBoxLayout()
        text_edit = QTextEdit()
        text_edit.setText("")
        layout.addWidget(text_edit)
        self.setLayout(layout)

        # 读取日志记录展示出来
        content = ""
        file_name = "{}.log".format(self.asin)
        file_path = logPath + file_name
        if os.path.exists(file_path):
            with open(file_path, mode="r", encoding="utf8") as fp:
                content = fp.read()

        text_edit.setText(content)
